document.addEventListener('DOMContentLoaded', () => {
  const searchInput = document.getElementById('searchInput');
  const searchBtn = document.getElementById('searchBtn');
  const resetBtn = document.getElementById('resetBtn');
  const taskTbody = document.getElementById('taskTbody');
  const totalTime = document.getElementById('totalTime');
  const pagination = document.getElementById('pagination');
  const startDateInput = document.getElementById('startDate');
  const endDateInput = document.getElementById('endDate');
  const statusSelect = document.getElementById('statusSelect');
  
  // 周报模态框相关元素
  const generateReportBtn = document.getElementById('generateReportBtn');
  const reportModal = document.getElementById('reportModal');
  const closeBtn = document.querySelector('.close');
  const closeModalBtn = document.getElementById('closeModalBtn');
  const reportContent = document.getElementById('reportContent');
  const copyReportBtn = document.getElementById('copyReportBtn');

  let allTasks = [];
  let filteredTasks = [];
  let currentPage = 1;
  const pageSize = 10;

  // 新增：默认设置为本周一和本周日
  const today = new Date();
  const day = today.getDay(); // 0=周日, 1=周一, ...
  const monday = new Date(today);
  monday.setDate(today.getDate() - ((day + 6) % 7));
  const sunday = new Date(monday);
  sunday.setDate(monday.getDate() + 6);
  function formatDate(d) {
    const yyyy = d.getFullYear();
    const mm = String(d.getMonth() + 1).padStart(2, '0');
    const dd = String(d.getDate()).padStart(2, '0');
    return `${yyyy}-${mm}-${dd}`;
  }
  startDateInput.value = formatDate(monday);
  endDateInput.value = formatDate(sunday);

  function formatDateTime(dt) {
    if (!dt) return '';
    const d = new Date(dt);
    return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')} ${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}`;
  }
  function formatDurationFromSegments(timerSegments) {
    if (!Array.isArray(timerSegments) || timerSegments.length === 0) return '';
    let totalMs = 0;
    timerSegments.forEach(seg => {
      if (seg.start && seg.end) {
        totalMs += new Date(seg.end) - new Date(seg.start);
      }
    });
    let min = Math.floor(totalMs / 60000);
    let sec = Math.floor((totalMs % 60000) / 1000);
    if (min < 1) {
      return `${sec}s`;
    }
    if (min < 60) {
      return sec > 0 ? `${min}min/${sec}s` : `${min}min`;
    } else {
      const h = Math.floor(min / 60);
      const m = min % 60;
      if (sec > 0) {
        return m === 0 ? `${h}h/${sec}s` : `${h}h/${m}min/${sec}s`;
      }
      if (m === 0) return `${h}h`;
      return `${h}h/${m}min`;
    }
  }

  function sortTasks(tasks) {
    // 进行中 > 待处理 > 已完成
    const inProgress = tasks.filter(t => t.status === '进行中').sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
    const pending = tasks.filter(t => t.status === '待处理');
    const done = tasks.filter(t => t.status === '已完成').sort((a, b) => new Date(b.completedAt) - new Date(a.completedAt));
    return [...inProgress, ...pending, ...done];
  }

  function renderStats() {
    // Total stats
    const total = allTasks.length;
    const totalPending = allTasks.filter(t => t.status === '待处理').length;
    const totalInProgress = allTasks.filter(t => t.status === '进行中').length;
    const totalDone = allTasks.filter(t => t.status === '已完成').length;
    // Current filter stats
    const cur = filteredTasks.length;
    const curPending = filteredTasks.filter(t => t.status === '待处理').length;
    const curInProgress = filteredTasks.filter(t => t.status === '进行中').length;
    const curDone = filteredTasks.filter(t => t.status === '已完成').length;
    document.getElementById('statsBar').innerHTML =
      `<div style='flex:1;min-width:220px;'>
        <b>All Tasks</b><br>
        <span style='font-size:15px;'>${total}</span>
        <span style='margin-left:8px;color:#faad14;'>Pending: ${totalPending}</span>
        <span style='margin-left:8px;color:#1677ff;'>In Progress: ${totalInProgress}</span>
        <span style='margin-left:8px;color:#52c41a;'>Done: ${totalDone}</span>
      </div>
      <div style='flex:1;min-width:220px;'>
        <b>Current Filter</b><br>
        <span style='font-size:15px;'>${cur}</span>
        <span style='margin-left:8px;color:#faad14;'>Pending: ${curPending}</span>
        <span style='margin-left:8px;color:#1677ff;'>In Progress: ${curInProgress}</span>
        <span style='margin-left:8px;color:#52c41a;'>Done: ${curDone}</span>
      </div>`;
  }

  function renderTasks(tasks, page = 1) {
    renderStats();
    const sorted = sortTasks(tasks);
    taskTbody.innerHTML = '';
    const startIdx = (page - 1) * pageSize;
    const endIdx = startIdx + pageSize;
    const pageTasks = sorted.slice(startIdx, endIdx);
    let total = 0;
    pageTasks.forEach(task => {
      let duration = '';
      if (task.status === '已完成' && Array.isArray(task.timerSegments)) {
        duration = formatDurationFromSegments(task.timerSegments);
        total += Math.round(task.timerSegments.reduce((sum, seg) => {
          if (seg.start && seg.end) {
            return sum + (new Date(seg.end) - new Date(seg.start)) / 60000;
          }
          return sum;
        }, 0));
      }
      const tr = document.createElement('tr');
      // 状态英文映射
      let statusEn = '';
      switch (task.status) {
        case '待处理': statusEn = 'Pending'; break;
        case '进行中': statusEn = 'In Progress'; break;
        case '已完成': statusEn = 'Completed'; break;
        case '已取消': statusEn = 'Cancelled'; break;
        default: statusEn = task.status || ''; break;
      }
      tr.innerHTML = `
        <td>${task.title || ''}</td>
        <td>${statusEn}</td>
        <td>${task.description ? task.description.replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/\n/g,'<br>') : ''}</td>
        <td>${duration}</td>
        <td>${task.createdAt ? formatDateTime(task.createdAt) : ''}</td>
        <td>${task.completedAt ? formatDateTime(task.completedAt) : ''}</td>
      `;
      taskTbody.appendChild(tr);
    });
    // 总耗时统计所有已完成任务
    let totalMs = 0;
    tasks.forEach(t => {
      if (t.status === '已完成' && Array.isArray(t.timerSegments)) {
        t.timerSegments.forEach(seg => {
          if (seg.start && seg.end) {
            totalMs += new Date(seg.end) - new Date(seg.start);
          }
        });
      }
    });
    let totalMin = Math.floor(totalMs / 60000);
    let totalSec = Math.floor((totalMs % 60000) / 1000);
    let totalStr = '';
    if (totalMin < 1) {
      totalStr = `${totalSec}s`;
    } else if (totalMin < 60) {
      totalStr = totalSec > 0 ? `${totalMin}min/${totalSec}s` : `${totalMin}min`;
    } else {
      const h = Math.floor(totalMin / 60);
      const m = totalMin % 60;
      if (totalSec > 0) {
        totalStr = m === 0 ? `${h}h/${totalSec}s` : `${h}h/${m}min/${totalSec}s`;
      } else {
        totalStr = m === 0 ? `${h}h` : `${h}h/${m}min`;
      }
    }
    totalTime.textContent = totalStr;
    renderPagination(tasks.length, page);
  }

  function renderPagination(total, page) {
    pagination.innerHTML = '';
    const pageCount = Math.ceil(total / pageSize);
    if (pageCount <= 1) return;
    for (let i = 1; i <= pageCount; i++) {
      const btn = document.createElement('button');
      btn.textContent = i;
      if (i === page) btn.className = 'active';
      btn.onclick = () => {
        currentPage = i;
        renderTasks(filteredTasks, currentPage);
      };
      pagination.appendChild(btn);
    }
  }

  function filterTasks(keyword, startDate, endDate, status) {
    let result = allTasks;
    
    // 关键词筛选应用于所有任务
    if (keyword) {
      result = result.filter(task => {
        return (task.title && task.title.includes(keyword)) ||
               (task.description && task.description.includes(keyword));
      });
    }
    
    // 如果明确选择了状态筛选，则应用所有筛选条件
    if (status) {
      // 英文转中文映射
      let statusZh = '';
      switch (status) {
        case 'Pending': statusZh = '待处理'; break;
        case 'In Progress': statusZh = '进行中'; break;
        case 'Completed': statusZh = '已完成'; break;
        case 'Cancelled': statusZh = '已取消'; break;
        default: statusZh = ''; break;
      }
      // 应用状态筛选
      result = result.filter(task => task.status === statusZh);
      
      // 对已经按状态筛选的结果应用日期筛选
      if (startDate) {
        const start = new Date(startDate);
        result = result.filter(task => {
          if (!task.createdAt) return true; // 没有开始时间的任务也保留
          return new Date(task.createdAt) >= start;
        });
      }
      if (endDate) {
        const end = new Date(endDate);
        end.setHours(23,59,59,999);
        result = result.filter(task => {
          if (!task.createdAt) return true; // 没有开始时间的任务也保留
          return new Date(task.createdAt) <= end;
        });
      }
    } 
    // 如果没有明确选择状态筛选，则默认保留所有"进行中"的任务，其他任务应用日期筛选
    else {
      // 分离"进行中"任务和其他任务
      const inProgressTasks = result.filter(task => task.status === '进行中');
      let otherTasks = result.filter(task => task.status !== '进行中');
      
      // 对其他任务应用日期筛选
      if (startDate) {
        const start = new Date(startDate);
        otherTasks = otherTasks.filter(task => {
          if (!task.createdAt) return true;
          return new Date(task.createdAt) >= start;
        });
      }
      if (endDate) {
        const end = new Date(endDate);
        end.setHours(23,59,59,999);
        otherTasks = otherTasks.filter(task => {
          if (!task.createdAt) return true;
          return new Date(task.createdAt) <= end;
        });
      }
      
      // 合并结果
      result = [...inProgressTasks, ...otherTasks];
    }
    
    return result;
  }

  function loadTasks() {
    chrome.storage.local.get(['tasks'], (result) => {
      allTasks = result.tasks || [];
      // 首次加载时应用日期过滤器
      const startDate = startDateInput.value;
      const endDate = endDateInput.value;
      filteredTasks = filterTasks('', startDate, endDate, '');
      currentPage = 1;
      renderTasks(filteredTasks, currentPage);
    });
  }

  searchBtn.onclick = () => {
    const keyword = searchInput.value.trim();
    const startDate = startDateInput.value;
    const endDate = endDateInput.value;
    const status = statusSelect.value;
    filteredTasks = filterTasks(keyword, startDate, endDate, status);
    currentPage = 1;
    renderTasks(filteredTasks, currentPage);
  };

  resetBtn.onclick = () => {
    searchInput.value = '';
    startDateInput.value = '';
    endDateInput.value = '';
    statusSelect.value = '';
    filteredTasks = allTasks;
    currentPage = 1;
    renderTasks(filteredTasks, currentPage);
  };

  // 宽度切换功能
  const adminContainer = document.getElementById('adminContainer');
  const widthToggleBtn = document.getElementById('widthToggleBtn');
  const widthIcon = document.getElementById('widthIcon');
  // 两种宽度
  const widths = [
    '1100px', // 原始
    '1400px'  // 最宽
  ];
  let widthIdx = 0;
  function setAdminWidth(idx) {
    adminContainer.style.maxWidth = widths[idx];
    adminContainer.style.width = '100%';
  }
  setAdminWidth(widthIdx);
  if (widthToggleBtn) {
    widthToggleBtn.onclick = function() {
      widthIdx = (widthIdx + 1) % widths.length;
      setAdminWidth(widthIdx);
    };
  }

  // 周报生成功能
  function generateWeeklyReport() {
    // 确保时间是本周的
    const startDate = startDateInput.value;
    const endDate = endDateInput.value;
    
    // 根据当前的筛选条件筛选任务
    const keyword = searchInput.value.trim();
    const status = statusSelect.value;
    const weekTasks = filterTasks(keyword, startDate, endDate, status);
    
    // 按照完成状态分组任务
    const completed = weekTasks.filter(t => t.status === '已完成');
    const inProgress = weekTasks.filter(t => t.status === '进行中');
    const pending = weekTasks.filter(t => t.status === '待处理');
    
    // 计算总工作时长
    let totalMs = 0;
    completed.forEach(t => {
      if (Array.isArray(t.timerSegments)) {
        t.timerSegments.forEach(seg => {
          if (seg.start && seg.end) {
            totalMs += new Date(seg.end) - new Date(seg.start);
          }
        });
      }
    });
    
    // 格式化总工作时长
    let totalHours = Math.floor(totalMs / 3600000);
    let totalMinutes = Math.floor((totalMs % 3600000) / 60000);
    let totalTimeStr = totalHours > 0 
      ? `${totalHours} hours${totalMinutes > 0 ? ' ' + totalMinutes + ' minutes' : ''}`
      : `${totalMinutes} minutes`;
    
    // 获取周一和周日的日期
    const mondayDate = new Date(startDate);
    const sundayDate = new Date(endDate);
    
    // 简化任务分类展示的函数
    function renderTaskList(tasks, prefix = '') {
      return tasks.map(task => {
        const duration = task.timerSegments ? formatDurationFromSegments(task.timerSegments) : '';
        return `- ${prefix}${task.title}${duration ? ' (Time spent: ' + duration + ')' : ''}`;
      }).join('\n');
    }
    
    // 生成周报内容
    let report = `# Weekly Work Report (${formatDate(mondayDate)} to ${formatDate(sundayDate)})\n\n`;
    
    // 本周工作总结
    report += `## I. Weekly Summary\n`;
    report += `This week: Completed ${completed.length} tasks, ${inProgress.length} in progress, ${pending.length} pending. Total work time: approximately ${totalTimeStr}.\n\n`;
    
    // 已完成任务
    if (completed.length > 0) {
      report += `### 1. Completed Tasks\n`;
      report += renderTaskList(completed) + '\n\n';
    }
    
    // 进行中任务
    if (inProgress.length > 0) {
      report += `### 2. Tasks in Progress\n`;
      report += renderTaskList(inProgress) + '\n\n';
    }
    
    // 待处理任务
    if (pending.length > 0) {
      report += `### 3. Pending Tasks\n`;
      const displayPending = pending.slice(0, Math.min(3, pending.length));
      report += renderTaskList(displayPending);
      if (pending.length > 3) {
        report += `\n- And ${pending.length - 3} more pending tasks`;
      }
      report += '\n\n';
    }
    
    // 下周计划
    report += `## II. Next Week Plan\n`;
    
    let hasPlan = false;
    // 添加进行中的任务作为下周计划
    if (inProgress.length > 0) {
      report += renderTaskList(inProgress, 'Continue working on: ');
      hasPlan = true;
    }
    
    // 添加一些待处理任务
    if (pending.length > 0) {
      const planTasks = pending.slice(0, Math.min(5, pending.length));
      if (hasPlan) report += '\n';
      report += renderTaskList(planTasks, 'Start working on: ');
      hasPlan = true;
    }
    
    report += '\n\n';
    
    // 问题和建议
    report += `## III. Issues and Suggestions\n`;
    report += `- None at the moment\n\n`;
    
    // 添加一个签名
    const today = new Date();
    const todayStr = `${today.getFullYear()}-${String(today.getMonth()+1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
    report += `Reported by:\nDate: ${todayStr}`;
    
    return report;
  }
  
  // 周报模态框相关事件处理
  if (generateReportBtn) {
    generateReportBtn.onclick = function() {
      // 显示加载状态
      const originalSvg = generateReportBtn.innerHTML;
      generateReportBtn.innerHTML = `
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#1677ff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="loading-icon">
          <circle cx="12" cy="12" r="10"></circle>
          <path d="M12 6v6l4 2"></path>
        </svg>
      `;
      generateReportBtn.style.pointerEvents = 'none';
      
      // 使用setTimeout让UI有时间更新
      setTimeout(() => {
        try {
          // 生成周报内容
          const reportMarkdown = generateWeeklyReport();
          
          // 将Markdown转换为HTML显示
          const reportHtml = convertMarkdownToHtml(reportMarkdown);
          reportContent.innerHTML = reportHtml;
          
          // 保存原始Markdown内容用于复制
          reportContent.setAttribute('data-markdown', reportMarkdown);
        } catch (error) {
          console.error('Error generating report:', error);
          alert('An error occurred while generating the report. Please try again later.');
        } finally {
          // 恢复按钮状态
          generateReportBtn.innerHTML = originalSvg;
          generateReportBtn.style.pointerEvents = 'auto';
          
          // 显示模态框
          reportModal.style.display = 'block';
        }
      }, 300); // 短暂延迟，让用户感知到有操作
    };
  }
  
  // 关闭模态框
  if (closeBtn) {
    closeBtn.onclick = function() {
      reportModal.style.display = 'none';
    };
  }
  
  if (closeModalBtn) {
    closeModalBtn.onclick = function() {
      reportModal.style.display = 'none';
    };
  }
  
  // 点击模态框外部关闭
  window.onclick = function(event) {
    if (event.target === reportModal) {
      reportModal.style.display = 'none';
    }
  };
  
  // 复制周报内容
  if (copyReportBtn) {
    copyReportBtn.onclick = function() {
      // 获取原始Markdown内容
      const markdownContent = reportContent.getAttribute('data-markdown');
      
      // 创建临时textarea来复制文本
      const tempTextarea = document.createElement('textarea');
      tempTextarea.value = markdownContent;
      document.body.appendChild(tempTextarea);
      tempTextarea.select();
      document.execCommand('copy');
      document.body.removeChild(tempTextarea);
      
      // 显示复制成功提示
      const originalText = copyReportBtn.textContent;
      copyReportBtn.textContent = 'Copied!';
      setTimeout(() => {
        copyReportBtn.textContent = originalText;
      }, 2000);
    };
  }

  // 简单的Markdown转HTML函数
  function convertMarkdownToHtml(markdown) {
    if (!markdown) return '';
    
    // 处理标题
    let html = markdown
      .replace(/^# (.*?)$/gm, '<h1>$1</h1>')
      .replace(/^## (.*?)$/gm, '<h2>$1</h2>')
      .replace(/^### (.*?)$/gm, '<h3>$1</h3>')
      .replace(/^#### (.*?)$/gm, '<h4>$1</h4>');
    
    // 处理分隔线
    html = html.replace(/^\-\-\-+$/gm, '<hr>');
    
    // 处理列表项
    const listItemRegex = /^- (.*?)$/gm;
    html = html.replace(listItemRegex, (match, content) => {
      // 处理列表项中的嵌套内容
      if (content.includes('\n    -')) {
        content = content.replace(/\n    - /g, '\n  <li>') + '\n  </li>';
        return `<li>${content}</li>`;
      }
      return `<li>${content}</li>`;
    });
    
    // 将连续的列表项包装在ul标签内
    html = html.replace(/(<li>.*?<\/li>\n)+/gs, match => {
      return `<ul>${match}</ul>`;
    });
    
    // 处理段落
    const paragraphs = html.split('\n\n');
    html = paragraphs.map(p => {
      // 跳过已经处理的元素
      if (p.trim().startsWith('<h') || 
          p.trim().startsWith('<ul') || 
          p.trim().startsWith('<hr')) {
        return p;
      }
      return `<p>${p.replace(/\n/g, '<br>')}</p>`;
    }).join('\n');
    
    // 处理粗体
    html = html.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
    
    // 处理斜体
    html = html.replace(/\*(.*?)\*/g, '<em>$1</em>');
    
    // 处理行内代码
    html = html.replace(/`(.*?)`/g, '<code>$1</code>');
    
    return html;
  }

  loadTasks();
}); 